package cn.tanglong.pet.controller;

import cn.tanglong.basic.exception.MyException;
import cn.tanglong.basic.util.AjaxResult;
import cn.tanglong.basic.util.PageList;
import cn.tanglong.pet.domain.Pet;
import cn.tanglong.pet.query.PetQuery;
import cn.tanglong.pet.service.IPetService;
import jdk.nashorn.api.scripting.AbstractJSObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/pet")
public class PetController {

    @Autowired
    private IPetService petService;


    // 加载宠物列表
    @PostMapping("/pagelist")
    public AjaxResult pagelist(@RequestBody PetQuery query){
        try {
            PageList pageList = petService.queryList(query);
            return AjaxResult.me().setResultObj(pageList);
        } catch (MyException e){
            e.printStackTrace();
            return AjaxResult.me().setMsg(e.getMessage());
        } catch (Exception e){
            e.printStackTrace();
            return AjaxResult.me().setMsg("后端pagelist失败！");
        }
    }

    // 上架
    @PostMapping("/onsale")
    public AjaxResult onsale(@RequestBody List<Long> ids){
        try {
            petService.onsale(ids);
            return AjaxResult.me();
        } catch (MyException e) {
            e.printStackTrace();
            return AjaxResult.me().setMsg(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMsg("onsale失败！");
        }
    }

    // 下架
    @PostMapping("/offsale")
    public AjaxResult offsale(@RequestBody List<Long> ids){
        try {
            petService.offsale(ids);
            return AjaxResult.me();
        } catch (MyException e) {
            e.printStackTrace();
            return AjaxResult.me().setMsg(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMsg("onsale失败！");
        }
    }

    // 加载线上的宠物列表
    @PostMapping("/petselect")
    public AjaxResult petselect(@RequestBody PetQuery query){
        try {
            PageList<Pet> petPageList = petService.queryList(query);
            return AjaxResult.me().setResultObj(petPageList);
        } catch (MyException e) {
            e.printStackTrace();
            return AjaxResult.me().setMsg(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMsg("接口报错！");
        }
    }

    /* 查询已经上线的宠物 */
    @GetMapping("/selectOnLineById/{id}")
    public AjaxResult selectOnLineById(@PathVariable Long id){
        try {
            Pet pet = petService.selectOnLineById(id);
            return AjaxResult.me().setResultObj(pet);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMsg("contro失败！");
        }
    }
}
